<template>
	<view class="audioview" @tap="openAudio">
		{{audiodata.duration}}"
		<cl-trumpet :isPlay="audioPlaying"></cl-trumpet>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex'
	export default {
		props: {
			audiodata: {
				type: Object,
				default(){
					return {}
				}
			},
			msg_id:{
				type:String,
				default:''
			}
		},
		data() {
			return {
				audioPlaying: false,
				innerAudioContext: null,
			}
		},
		methods: {
			...mapActions(['audioOn', 'audioEmit', 'audioOff']),
			// 监听播放音频全局事件
			onPlayAudio(msg_id) {
				if (this.innerAudioContext) {
					if (this.msg_id != msg_id) {
						this.innerAudioContext.stop()
					}
				}
			},
			// 播放音频
			openAudio() {
				// 通知停止其他音频
				this.audioEmit(this.msg_id)
				if (!this.innerAudioContext) {
					this.innerAudioContext = uni.createInnerAudioContext();
					this.innerAudioContext.src = this.audiodata.url
					this.innerAudioContext.play()
					// 监听播放
					this.innerAudioContext.onPlay(() => {
						this.audioPlaying = true
					})
					// 监听暂停
					this.innerAudioContext.onPause(() => {
						this.audioPlaying = false
					})
					// 监听停止
					this.innerAudioContext.onStop(() => {
						this.audioPlaying = false
					})
					this.innerAudioContext.onEnded(() => {
						this.audioPlaying = false
					})
					// 监听错误
					this.innerAudioContext.onError((e) => {
						uni.showToast({
							title:e.errMsg,
							icon:'none'
						})
						this.audioPlaying = false
					})
				} else {
					if (this.audioPlaying) {
						this.innerAudioContext.stop()
					} else {
						this.innerAudioContext.play()
					}
				}
			},
		},
		mounted(){
			
			// 注册全局事件
			this.audioOn(this.onPlayAudio)
		},
		// 组件销毁
		destroyed() {
			this.audioOff(this.onPlayAudio)
			// 销毁音频
			if (this.innerAudioContext) {
				this.innerAudioContext.destroy()
				this.innerAudioContext = null
			}
		},
	}
</script>

<style scoped>
	.audioview{
		display: flex;
		align-items: center;
	}
</style>
